package client.messages;

import client.messages.commands.ConsoleCommand;
import client.messages.commands.ConsoleCommandExecute;
import client.messages.commands.ConsoleCommandObject;
import tools.FilePrinter;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class ConsoleCommandProcessor {
    private static HashMap<String, ConsoleCommandObject> commands;

    private static void sendDisplayMessage(String msg) {
        System.err.println("[sendDisplayMessage]错误:" + msg);
    }

    public static boolean processCommand(String line) {
        String[] splitted = line.split(" ");
        splitted[0] = splitted[0].toLowerCase();
        ConsoleCommandObject co = (ConsoleCommandObject) ConsoleCommandProcessor.commands.get(splitted[0]);
        if (co == null) {
            sendDisplayMessage("沒有这个指令.");
            return true;
        }
        int ret = co.execute(splitted);
        return true;
    }

    static {
        commands = new HashMap();
        Class[] array;
        Class<?>[] CommandFiles = (Class<?>[]) (array = new Class[]{ConsoleCommand.class});
        for (Class<?> clasz : array) {
            try {
                Class<?>[] a = clasz.getDeclaredClasses();
                ArrayList<String> cL = (ArrayList<String>) new ArrayList();
                for (Class<?> c : a) {
                    try {
                        if (!Modifier.isAbstract(c.getModifiers()) && !c.isSynthetic()) {
                            Object o = c.newInstance();
                            boolean enabled;
                            try {
                                enabled = c.getDeclaredField("enabled").getBoolean(c.getDeclaredField("enabled"));
                            } catch (NoSuchFieldException ex3) {
                                enabled = true;
                            }
                            if (o instanceof ConsoleCommandExecute && enabled) {
                                cL.add(c.getSimpleName().toLowerCase());
                                commands.put(c.getSimpleName().toLowerCase(), new ConsoleCommandObject(c.getSimpleName().toLowerCase(), (ConsoleCommandExecute) o));
                            }
                        }
                    } catch (InstantiationException | IllegalAccessException | SecurityException |
                             IllegalArgumentException ex5) {
                        FilePrinter.printError("ConsoleCommandProcessor.txt", (Throwable) ex5);
                    }
                }
                Collections.sort((List<String>) cL);
            } catch (Exception ex2) {
                FilePrinter.printError("ConsoleCommandProcessor.txt", (Throwable) ex2);
            }
        }
    }
}
